<script setup lang="ts">
  import DynamicForm from '@/components/common/dynamicForm/DynamicForm.vue';
  import { DynamicFormOption, DynamicItem, DynamicSelectOption } from '@/components/types';
  import { useLocale } from '@/locales/useLocale';
  import { useMobile } from '@/hooks/core/useMobile';
  import { computed, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { useUserinfoStore } from '@/store/module/useUserStore';
  import { IUpdatePasswordParam } from '@/api/types';
  import { useGo } from '@/hooks/router';
  import { HeaderRouterPath } from '@/router/types';
  import { useAuthStore } from '@/store/module/useAuthStore';
  const { t } = useLocale();
  const schema = {
    oldPwd: 'required',
    newPwd: 'required',
    confirmedPassword: 'required|confirmed:@newPwd',
  };
  const initValues = {
    oldPwd: '',
    newPwd: '',
    confirmedPassword: '',
  };
  const updatePasswordFormOption = [
    {
      is: DynamicItem.INPUT,
      name: 'oldPwd',
      placeholder: 'message.sys.login.oldPassword',
      requiredField: true,
      type: 'password',
      showPassword: true,
    },
    {
      is: DynamicItem.INPUT,
      name: 'newPwd',
      placeholder: 'message.sys.login.newPassword',
      requiredField: true,
      type: 'password',
      showPassword: true,
    },
    {
      is: DynamicItem.INPUT,
      name: 'confirmedPassword',
      placeholder: 'message.sys.login.confirmPassword',
      requiredField: true,
      type: 'password',
      showPassword: true,
    },
  ] as DynamicFormOption[];
  const loading = ref(false);
  const userStore = useUserinfoStore();
  const authStore = useAuthStore();
  const go = useGo();
  const onSubmit = (values: IUpdatePasswordParam, formTool: Recordable) => {
    ElMessageBox.confirm(
      t('message.sys.profile.reviseInfoMessage'),
      t('message.sys.profile.reviseInfo'),
      {
        confirmButtonText: t('message.common.okText'),
        cancelButtonText: t('message.common.cancelText'),
      }
    ).then(() => {
      loading.value = true;
      userStore.updatePassword(values, (isSuccess: boolean) => {
        formTool.resetForm();
        loading.value = false;
        if (isSuccess) {
          ElMessage.success({ message: '修改密码成功，请重新登录！' });
          authStore.logout();
          go(HeaderRouterPath.HOME);
        }
      });
    });
  };
  const isMobile = useMobile();
  const size = computed(() => {
    return isMobile.value ? 'default' : 'large';
  });
</script>

<template>
  <DynamicForm
    as="ElForm"
    :validation-schema="schema"
    :initialValues="initValues"
    :options="updatePasswordFormOption"
    @on-submit="onSubmit"
    :size="size"
    :loading="loading"
    animate-class="enter-y"
    submit-content="message.sys.login.forgetFormTitle"
  />
</template>

<style lang="scss"></style>
